package com.srmt.user.examples;

import com.srmt.user.api.UserIdResolver;
import com.srmt.user.factory.UserIdResolverFactory;
import com.srmt.user.exception.UserServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * 批量获取用户ID示例
 * 
 * 演示如何使用批量API通过电话号码获取用户ID
 * 
 * @author SRMT Development Team
 * @since 1.5.0
 */
public class BatchUserIdResolverExample {
    
    private static final Logger logger = LoggerFactory.getLogger(BatchUserIdResolverExample.class);
    
    public static void main(String[] args) {
        try {
            // 1. 创建用户ID解析器
            UserIdResolver userResolver = UserIdResolverFactory.createDefault();
            
            // 2. 准备要查询的电话号码列表
            List<String> phoneNumbers = Arrays.asList(
                "+86-13800138000",  // 带国家码格式
                "13900139000",      // 纯数字格式
                "+86 137 0013 7000", // 带空格格式
                "13600136000",      // 普通手机号
                "+86-13500135000"   // 带横线格式
            );
            
            logger.info("准备批量查询 {} 个电话号码", phoneNumbers.size());
            
            // 3. 批量查询用户ID
            Map<String, String> userIdMap = userResolver.getUserIdsByPhones(phoneNumbers);
            
            // 4. 处理查询结果
            logger.info("成功找到 {} 个用户", userIdMap.size());
            
            for (Map.Entry<String, String> entry : userIdMap.entrySet()) {
                String phone = entry.getKey();
                String userId = entry.getValue();
                logger.info("电话号码: {} -> 用户ID: {}", phone, userId);
            }
            
            // 5. 检查未找到的用户
            for (String phone : phoneNumbers) {
                if (!userIdMap.containsKey(phone)) {
                    logger.warn("未找到用户: {}", phone);
                }
            }
            
            // 演示其他使用场景
            demonstratePermissionSetting(userResolver);
            demonstrateCachePerformance(userResolver);
            
        } catch (UserServiceException e) {
            logger.error("批量查询用户失败", e);
        } catch (Exception e) {
            logger.error("示例执行失败", e);
        }
    }
    
    /**
     * 演示批量设置文档权限的场景
     */
    private static void demonstratePermissionSetting(UserIdResolver userResolver) throws Exception {
        logger.info("\n=== 演示批量设置文档权限场景 ===");
        
        // 准备需要授权的用户电话列表
        List<String> adminPhones = Arrays.asList(
            "+86-13800138001",
            "+86-13800138002"
        );
        
        List<String> editorPhones = Arrays.asList(
            "+86-13900139001",
            "+86-13900139002",
            "+86-13900139003"
        );
        
        List<String> viewerPhones = Arrays.asList(
            "+86-13700137001",
            "+86-13700137002",
            "+86-13700137003",
            "+86-13700137004"
        );
        
        // 批量获取管理员用户ID
        Map<String, String> adminIds = userResolver.getUserIdsByPhones(adminPhones);
        logger.info("找到 {} 个管理员用户", adminIds.size());
        
        // 批量获取编辑者用户ID
        Map<String, String> editorIds = userResolver.getUserIdsByPhones(editorPhones);
        logger.info("找到 {} 个编辑用户", editorIds.size());
        
        // 批量获取查看者用户ID
        Map<String, String> viewerIds = userResolver.getUserIdsByPhones(viewerPhones);
        logger.info("找到 {} 个查看用户", viewerIds.size());
        
        // 这些用户ID可以用于设置文档权限
        logger.info("总共准备了 {} 个用户权限设置", 
            adminIds.size() + editorIds.size() + viewerIds.size());
    }
    
    /**
     * 演示缓存性能提升
     */
    private static void demonstrateCachePerformance(UserIdResolver userResolver) throws Exception {
        logger.info("\n=== 演示缓存性能提升 ===");
        
        List<String> testPhones = Arrays.asList(
            "+86-13800138000",
            "+86-13900139000",
            "+86-13700137000"
        );
        
        // 第一次查询（需要调用API）
        long start = System.currentTimeMillis();
        Map<String, String> result1 = userResolver.getUserIdsByPhones(testPhones);
        long firstTime = System.currentTimeMillis() - start;
        logger.info("第一次查询耗时: {}ms，找到 {} 个用户", firstTime, result1.size());
        
        // 第二次查询（从缓存获取）
        start = System.currentTimeMillis();
        Map<String, String> result2 = userResolver.getUserIdsByPhones(testPhones);
        long secondTime = System.currentTimeMillis() - start;
        logger.info("第二次查询耗时: {}ms，找到 {} 个用户", secondTime, result2.size());
        
        if (secondTime < firstTime) {
            double improvement = ((double)(firstTime - secondTime) / firstTime) * 100;
            logger.info("缓存性能提升: {:.1f}%", improvement);
        }
    }
    
    /**
     * 演示错误处理
     */
    private static void demonstrateErrorHandling(UserIdResolver userResolver) {
        logger.info("\n=== 演示错误处理 ===");
        
        try {
            // 测试包含无效数据的列表
            List<String> invalidPhones = Arrays.asList(
                null,
                "",
                "   ",
                "invalid-phone",
                "+86-13800138000"  // 只有这个是有效的
            );
            
            Map<String, String> result = userResolver.getUserIdsByPhones(invalidPhones);
            logger.info("处理包含无效数据的列表，成功找到 {} 个用户", result.size());
            
        } catch (UserServiceException e) {
            logger.error("批量查询失败: {}", e.getMessage());
        }
    }
}